<?php
// +----------------------------------------------------------------------
// | Site:  [ http://www.yzmcms.com]
// +----------------------------------------------------------------------
// | Copyright: 袁志蒙工作室，并保留所有权利
// +----------------------------------------------------------------------
// | Author: YuanZhiMeng <214243830@qq.com>
// +---------------------------------------------------------------------- 
// | Explain: 这不是一个自由软件,您只能在不用于商业目的的前提下对程序代码进行修改和使用，不允许对程序代码以任何形式任何目的的再发布！
// +----------------------------------------------------------------------

defined('IN_YZMPHP') or exit('Access Denied'); 
yzm_base::load_controller('common', 'admin', 0);
yzm_base::load_sys_class('page','',0);
yzm_base::load_common('class/xlswriter.class.php');

class collect_fish extends common {

	/**
	 * 配置信息
	 */
	
	public $config;
	public $data=[];
	public $field_map = [];
	public $need_field = ['*平台','*店铺全称','*订单编号','*下单件数','*下单金额','*日期'];//上传文件需要字段
	public $need_field_key = ['platform','shop_id','order_id','order_num','order_price','order_date'];//上传文件字段对应数据库字段
	public $save_path = 'cache'.DIRECTORY_SEPARATOR.'fish_file';//保存路径
	public $priv_shop = [];//有权限店铺
	public $shop_list = [];//所有店铺列表
	public $shop_list_key = [];//所有店铺列表对应的店铺id
	
	public function __construct(){
		$this->field_map = get_setting();
		//店铺权限
		$d_shop = D('collect_shop');
		//分销商分组只读取改分销商有权限的店铺
		if($_SESSION['roleid']==4){
			$shop_list = $d_shop->where('FIND_IN_SET('.$_SESSION['adminid'].', adminids) > 0')->select();
			$shop_name = array_column($shop_list, 'shop_name');
			$shop_id = array_column($shop_list, 'id');
			$this->priv_shop=['shop_name'=>$shop_name,'shop_id'=>$shop_id];
		}else{
			$shop_list = $d_shop->select();
			$shop_name = array_column($shop_list, 'shop_name');
			$shop_id = array_column($shop_list, 'id');
			$this->priv_shop=['shop_name'=>$shop_name,'shop_id'=>$shop_id];
			//$shop_list = array_column($shop_list, 'shop_name');
		}
		$shop_list_key = [];
		foreach($shop_list as $v){
			$shop_list_key[$v['id']] = $v['shop_name'];
		}
		$this->shop_list_key = $shop_list_key;
		parent::__construct();
	}

	//鱼塘单
	public function collect_fish(){
		$d_fish = D('collect_fish');
		$type = $_GET['type'] ?? '';
		if($type=='add'){
			if(is_post()){
				$result = $d_supplier->insert($_POST);
				if($result){
					return_json(array('status'=>1,'message'=>L('operation_success')));
				}else{
					return_json(array('status'=>0,'message'=>L('operation_failure')));
				}
			}
			include $this->admin_tpl('collect/collect_supplier_add');
			exit;
		}
		
		$page = input('get.page');
		$limit = input('get.limit');
		$of = input('get.field');
		$or = input('get.order');
		$shop_name = trim(input('get.shop_name'));
		$start = strtotime(trim(input('get.start')));
		$end = strtotime(trim(input('get.end')));
		$where = '1=1';
		if($shop_name){
			$where .=' AND s.shop_name like "%'.$shop_name.'%"';
		}
		if($start){
			$where .=' AND f.order_date >= '.$start;
		}
		if($end){
			$where .=' AND f.order_date < '.($end+86400);
		}
		$of = in_array($of, array('add_time')) ? $of : 'id';
		$or = in_array($or, array('asc','desc')) ? $or : 'desc';
		if($page){
			$total = $d_fish->alias('f')->join(C('db_prefix').'collect_shop s on s.id = f.shop_id','left')->where($where)->total();
			$page = new page($total, $limit);
			$this->data = $d_fish->alias('f')->field('f.*,s.id shop_id,s.shop_name,s.platform')->where($where)->join(C('db_prefix').'collect_shop s on s.id = f.shop_id','left')->order("$of $or")->limit($page->limit())->select();
			$this->_data_format();
			$data = ['code'=>0,'msg'=>'','count'=>$total,'data'=>$this->data];
			exit(json_encode($data));
		}
		include $this->admin_tpl('collect/collect_fish');
	}
	
	//鱼塘单导入
	public function fish_input(){
		//上传文件
		$filename = 'file';
		$path = YZMPHP_PATH.$this->save_path;
		yzm_base::load_model('host', 'attachment', 0);
		$option = ['filepath_full'=> $path,'allowtype'=>['xlsx','csv','xls']];
	    $upload = new host($option);
	    if($upload->uploadfile($filename)){
			//校验文件
	        $fileinfo = $upload->getnewfileinfo();
			$file = $path.DIRECTORY_SEPARATOR.$fileinfo['filename'];
			$config   = ['path' => $path];
			$excel    = new \Vtiful\Kernel\Excel($config);
			$data = $excel->openFile($fileinfo['filename'])->openSheet()->getSheetData();
			@unlink($file);
			//获取第一行数据校验必要字段
			$input_field = [];
			foreach($data[0] as $k=>$v){
				$input_field[$k] = $v;
			}
			$error_tip = '表格数据错误：<br/>';
			foreach($this->need_field as $v){
				if(!in_array($v,$input_field)){
					$error_tip .= '"'.$v.'"列不存在<br/>';
				}
			}
			if($error_tip!='表格数据错误：<br/>'){
				
				return_json(array('status'=>0,'message'=>$error_tip));
			}
			//导入数据array_search($valueToFind, $array)
			if(count($data)>5001){
				return_json(array('status'=>0,'message'=>'单次最多上传5000条数据'));
			}
			//字段映射
			$map=[];
			foreach($this->need_field as $k=>$v){
				foreach($input_field as $key=>$val){
					if($v==$val){
						$map[$key]=$k;
					}
				}
			}
			$list = [];
			$msg = '';
			foreach($data as $k=>$v){
				if($k==0) continue;
				$shop_name = '';
				foreach($v as $key=>$val){
					//对应字段读取
					$list[$k-1][$this->need_field_key[$map[$key]]]=trim($val);
					//校验店铺名称和权限
					if($this->need_field_key[$map[$key]] == 'shop_name'){
						$shop_name = $val;
						if(!empty($this->priv_shop)){
							if(!in_array($val,$this->priv_shop['shop_name'])){
								return_json(array('status'=>0,'message'=>'店铺名称应是：'.implode(',',$this->priv_shop['shop_name'])));
							}
						}else{
							if(!in_array($val,$this->shop_list)){
								return_json(array('status'=>0,'message'=>'店铺名称不存在：'.$val));
							}
						}
					}
					if($this->need_field_key[$map[$key]] == 'order_id'){
						//校验订单号是否上传过
						if(!$shop_name){
							return_json(array('status'=>0,'message'=>'店铺名称应在订单号前'));
						}
						$shop_id = array_search($shop_name,$this->shop_list_key);
						
						$info = D('collect_fish')->where(['order_id'=>$val,'shop_id'=>$shop_id])->find();
						if($info){
							$msg = '跳过订单已经存在：'.$val.'<br/>';
							unset($list[$k-1]);
							return_json(array('status'=>0,'message'=>'跳过订单已经存在：'.$val));
						}
					}
				}
			}
			print_r($list);exit;
			unset($data);
			$num = D('collect_fish')->insert_all($list);
			
			return_json(array('status'=>1,'message'=>'成功导入'.$num.'条数据<br/>'.$msg));
			
	    }else{
	        $info = array(
				"status" => 0,
	            "msg" => $upload->geterrormsg()
	        );
			return json_encode($info);
	    }
		
	}

	private function _data_format(){
		if(!$this->data){
			return [];
		}
		foreach($this->data as $k=>&$v){
			foreach($v as $key=>&$val){
				if($this->field_map['collect_'.$key]){
					$val = $this->field_map['collect_'.$key][$val];
				}
			}
		}
	}
}